<template>
  <div class="parking-records">
    <div class="page-header">
      <h2>我的停车记录</h2>
      <el-button type="primary" @click="goToParkingList">查找停车场</el-button>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="当前停车" name="current">
        <div v-if="currentParking" class="current-parking">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>当前停车信息</span>
                <el-button type="danger" @click="handleEndParking">结束停车</el-button>
              </div>
            </template>
            <div class="parking-info">
              <div class="info-item">
                <span class="label">停车场：</span>
                <span>{{ currentParking.parkingLotName }}</span>
              </div>
              <div class="info-item">
                <span class="label">开始时间：</span>
                <span>{{ formatDateTime(currentParking.startTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">已停时长：</span>
                <span>{{ formatDuration(currentParking.durationMinutes) }}</span>
              </div>
              <div class="info-item">
                <span class="label">预计费用：</span>
                <span class="fee">¥{{ calculateEstimatedFee(currentParking) }}</span>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无进行中的停车" />
      </el-tab-pane>

      <el-tab-pane label="历史记录" name="history">
        <el-table :data="parkingRecords" style="width: 100%">
          <el-table-column prop="parkingLotName" label="停车场" />
          <el-table-column prop="startTime" label="开始时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template #default="scope">
              {{ scope.row.endTime ? formatDateTime(scope.row.endTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="durationMinutes" label="停车时长">
            <template #default="scope">
              {{ formatDuration(scope.row.durationMinutes) }}
            </template>
          </el-table-column>
          <el-table-column prop="fee" label="费用">
            <template #default="scope">
              <span :class="{ 'overdue-fee': scope.row.isOverdue }">
                ¥{{ scope.row.fee || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 'COMPLETED'"
                type="primary" 
                link
                @click="viewDetails(scope.row.id)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 结束停车确认对话框 -->
    <el-dialog
      v-model="endParkingDialogVisible"
      title="结束停车"
      width="30%"
    >
      <div class="end-parking-info">
        <p>停车场：{{ currentParking?.parkingLotName }}</p>
        <p>开始时间：{{ currentParking ? formatDateTime(currentParking.startTime) : '' }}</p>
        <p>停车时长：{{ currentParking ? formatDuration(currentParking.durationMinutes) : '' }}</p>
        <p class="fee">费用：¥{{ currentParking ? calculateEstimatedFee(currentParking) : 0 }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="endParkingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEndParking">确认结束</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加支付对话框 -->
    <payment-dialog
      v-model="paymentDialogVisible"
      :payment-info="currentPayment"
      @success="handlePaymentSuccess"
      @cancel="handlePaymentCancel"
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserParkingRecords, endParking, calculateParkingFee } from '@/api/parking'
import { formatDateTime, formatDuration } from '@/utils/format'
import PaymentDialog from '@/components/payment/PaymentDialog.vue'

export default {
  name: 'ParkingRecords',
  components: {
    PaymentDialog
  },
  setup() {
    const router = useRouter()
    const activeTab = ref('current')
    const currentParking = ref(null)
    const parkingRecords = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const endParkingDialogVisible = ref(false)
    const paymentDialogVisible = ref(false)
    const currentPayment = ref(null)

    const loadParkingRecords = async () => {
      try {
        const response = await getUserParkingRecords({
          page: currentPage.value - 1,
          size: pageSize.value
        })
        parkingRecords.value = response.content
        total.value = response.totalElements

        // 查找当前停车记录
        currentParking.value = parkingRecords.value.find(
          record => record.status === 'PARKING'
        )
      } catch (error) {
        ElMessage.error('获取停车记录失败')
      }
    }

    const handleTabClick = () => {
      if (activeTab.value === 'history') {
        loadParkingRecords()
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadParkingRecords()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadParkingRecords()
    }

    const goToParkingList = () => {
      router.push('/parking/list')
    }

    const handleEndParking = async () => {
      try {
        const record = await endParking(currentParking.value.parkingLotId)
        
        // 计算费用
        const fee = await calculateParkingFee(record.id)
        
        // 显示支付对话框
        currentPayment.value = {
          id: record.id,
          parkingLotName: record.parkingLotName,
          startTime: record.startTime,
          endTime: record.endTime,
          durationMinutes: record.durationMinutes,
          amount: fee,
          isOverdue: record.isOverdue,
          overduePenalty: record.overduePenalty
        }
        paymentDialogVisible.value = true
      } catch (error) {
        ElMessage.error(error.message || '结束停车失败')
      }
    }

    const confirmEndParking = async () => {
      try {
        await endParking(currentParking.value.parkingLotId)
        ElMessage.success('结束停车成功')
        endParkingDialogVisible.value = false
        loadParkingRecords()
      } catch (error) {
        ElMessage.error(error.message || '结束停车失败')
      }
    }

    const viewDetails = (id) => {
      router.push(`/parking/records/${id}`)
    }

    const calculateEstimatedFee = (record) => {
      if (!record) return 0
      const durationHours = record.durationMinutes / 60
      return (durationHours * record.hourlyRate).toFixed(2)
    }

    const getStatusType = (status) => {
      const types = {
        PARKING: 'warning',
        COMPLETED: 'success',
        OVERDUE: 'danger'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        PARKING: '停车中',
        COMPLETED: '已完成',
        OVERDUE: '已逾期'
      }
      return texts[status] || status
    }

    const handlePaymentSuccess = () => {
      ElMessage.success('支付成功')
      loadParkingRecords()
    }

    const handlePaymentCancel = () => {
      ElMessageBox.confirm(
        '取消支付将导致停车记录未完成，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.info('已取消支付')
      }).catch(() => {
        paymentDialogVisible.value = true
      })
    }

    onMounted(() => {
      loadParkingRecords()
    })

    return {
      activeTab,
      currentParking,
      parkingRecords,
      currentPage,
      pageSize,
      total,
      endParkingDialogVisible,
      paymentDialogVisible,
      currentPayment,
      handleTabClick,
      handleSizeChange,
      handleCurrentChange,
      goToParkingList,
      handleEndParking,
      confirmEndParking,
      viewDetails,
      formatDateTime,
      formatDuration,
      calculateEstimatedFee,
      getStatusType,
      getStatusText,
      handlePaymentSuccess,
      handlePaymentCancel
    }
  }
}
</script>

<style scoped>
.parking-records {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.current-parking {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.parking-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #666;
  margin-right: 10px;
}

.fee {
  color: #f56c6c;
  font-weight: bold;
}

.overdue-fee {
  color: #f56c6c;
}

.end-parking-info {
  text-align: center;
}

.end-parking-info p {
  margin: 10px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 